/******************************************************************************
 * Copyright (C) 2017 Chengdu Dlhd information industry co. LTD.
 * All Rights Reserved.
 * 本软件为成都顶联互动信息产业有限公司开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、复制、修改或发布本软件.
 *****************************************************************************/
package net.dgg.dggcloud.service.jrcrm.service.customer.api;

import net.dgg.dggcloud.core.util.NJCodeUtil;
import net.dgg.dggcloud.core.util.StringUtils;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.common.exception.BizException;
import net.dgg.dggcloud.service.jrcrm.constant.BusinessConstant;
import net.dgg.dggcloud.service.jrcrm.constant.CustomerConstant;
import net.dgg.dggcloud.service.jrcrm.dao.customer.ContactDao;
import net.dgg.dggcloud.service.jrcrm.dao.customer.CustomerDao;
import net.dgg.dggcloud.service.jrcrm.entity.customer.Contact;
import net.dgg.dggcloud.service.jrcrm.entity.customer.Customer;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.jrcrm.service.business.BusinessAbilityService;
import net.dgg.dggcloud.service.jrcrm.service.customer.ContactService;
import net.dgg.dggcloud.service.jrcrm.service.customer.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;
import javax.jws.WebParam;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

 /**
  * 联系人业务处理-对外接口
 * @ClassName: ContactApiService
 * @Author: 周潮
 * @Date: 2017年11月03 14:40:18
 * @Version V1.0
 */

@Service
public class ContactApiService extends BaseService{

    @Resource
    private ContactDao contactDao;
    @Resource
    private CustomerDao customerDao;
    @Resource
    private ContactService contactService;
    @Resource
    private BusinessAbilityService businessAbilityService;
    @Resource
    private CustomerService customerService;
    @Resource
    private NJCodeUtil njCodeUtil;

    /**
     * 根据条件查询联系人列表
     * @param map
     * @return
     */
    public List<Map> queryCustomerListByParams(Map map){
        return contactDao.queryCustomerListByParams(map);
    }

     /**
      * 新增联系人
      * @param map 新增字段<br/>
      *            customerId：客户id<br/>
      *            contactName：联系人姓名<br/>
      *            contactNo：联系人电话号码<br/>
      *            contactWay：联系方式<br/>
      *            relationship：与客户的关系<br/>
      *            isMain：是否是主联系人<br/>
      *            User：操作人对象<br/>
      * @return
      */
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveContact(Map map){
        if(null == map.get("customerId")){
            throw new BizException("新增联系人失败！客户id为空！", 10005);
        }
        if(null == map.get("number")){
            throw new BizException("新增联系人失败！联系人号码为空！", 10005);
        }
        if(null == map.get("User")){
            throw new BizException("新增联系人失败！操作人信息不完整！", 10005);
        }
        //查询客户是否存在
        Customer customer = repository.get(Customer.class, Long.valueOf(map.get("customerId").toString()));
        User user = (User) map.get("User");
        if(null == customer){
            throw new BizException("新增联系人失败！客户不存在！", 10005);
        }

        Map params = new HashMap();
        params.put("contactWay", null == map.get("contactWay") ? CustomerConstant.CUS_CONTACT_WAY_MOBILE : map.get("contactWay").toString());
        params.put("customerNumber", map.get("number").toString());
        Integer repeatCount = contactDao.queryContactCountForJudgeRepeat(params);
        if(repeatCount >0 ) {
            throw new BizException("新增联系人失败！该号码已存在，不能重复添加！", 10005);
        }

        //保存联系人
        Contact contact = new Contact();
        long tid = this.keyWorker.nextId();
        contact.setId(tid);
        contact.setCustomerId(customer.getId());
        contact.setName(map.get("name").toString());
        contact.setNo(map.get("number").toString());
        contact.setNoBak(njCodeUtil.decrypt(map.get("number").toString()));
        contact.setContactWay(map.get("contactWay").toString());
        contact.setStatus("CUS_CONT_STATUS_1");//默认为可用状态
        contact.setRelationshipOfCus(map.get("relationshipOfCus").toString());
        //设置主联系人
        if(null != map.get("isMain") && Integer.parseInt(map.get("isMain").toString()) == 1){
            contactService.updateCusMainContact(contact, user, customer);//设置主联系人
        }else{
            repository.save(contact);
        }
        customerService.saveCustomerRecord(customer.getId(), customer.getNo(), Contact.TABLE_NAME, contact.getId(), CustomerConstant.CUS_OPERATE_CONTACT_SAVE, user.getId(), "新增联系人");
    }

    public void updateContactStatus(Map map){
        contactService.updateContactStatus(map);
    }

     /**
      * 设置主联系人
      * @param map
      * customerId
      * contactId
      * User
      * @return
      */
    @Transactional(propagation = Propagation.REQUIRED)
    public void setMainContact(Map map){
        if(null == map.get("contactId")){
            throw new BizException("设置主联系人失败！联系人不存在！", 10005);
        }
        if(null == map.get("User")){
            throw new BizException("设置主联系人失败！操作人信息不完整！", 10005);
        }
        if(null == map.get("User")){
            throw new BizException("设置主联系人失败！客户不存在！", 10005);
        }
        Contact contact = repository.get(Contact.class, Long.parseLong(map.get("contactId").toString()));
        User user = (User) map.get("User");
        Long customerId = Long.parseLong(map.get("customerId").toString());
        Customer customer = repository.get(Customer.class, customerId);
        if(null == customer){
            throw new BizException("设置主联系人失败！客户不存在！", 10005);
        }
        if(null == contact){
            throw new BizException("设置主联系人失败！联系人不存在！", 10005);
        }else{
            contact.setUpdaterUser(user);
            //设置主联系人
            contactService.updateCusMainContact(contact, user, customer);//设置主联系人
        }
        customerService.saveCustomerRecord(customerId, customer.getNo(), Contact.TABLE_NAME, contact.getId(), CustomerConstant.CUS_OPERATE_CONTACT_SAVE, user.getId(), "修改联系人");
    }

     /**
      * 下单修改联系人信息
      * @param map
      * name：姓名 </br>
      * cardId：身份证 </br>
      * no：电话号码 </br>
      * maritalStatus：婚姻状况 </br>
      * childrenNum：子女情况 </br>
      *customerId：客户id </br>
      *mainContactId：主联系人id </br>
      *relationshipOfCus：与客户关系 </br>
      *User：操作人 </br>
      * @return
      */
    @Transactional(propagation = Propagation.REQUIRED)
    public Long updateContact(Map map){
        if(null == map.get("contactInfo")){
            throw new BizException("修改联系人信息失败！联系人信息为空！", 10005);
        }
        if(null == map.get("User")){
            throw new BizException("修改联系人信息失败！操作人信息为空！", 10005);
        }
        if(null == map.get("customerId")){
            throw new BizException("修改联系人信息失败！客户不存在！", 10005);
        }
        List<Map> mapList = (List<Map>) map.get("contactInfo");
        User user = (User) map.get("User");
        Long customerId = Long.parseLong(map.get("customerId").toString());
        Customer customer = repository.get(Customer.class, customerId);
        if(null == customer){
            throw new BizException("修改联系人信息失败！客户不存在！", 10005);
        }
        if(null != mapList && mapList.size() > 0){
            for (int i =0; i < mapList.size(); i++){
                Map m = mapList.get(i);
                if(null == m.get("no")){
                    throw new BizException("修改联系人信 息失败！联系人号码为空！", 10005);
                }
                if(null == m.get("cardId")){
                    throw new BizException("修改联系人信息失败！身份证号码为空！", 10005);
                }
                if(null == m.get("name")){
                    throw new BizException("修改联系人信息失败！联系人姓名为空！", 10005);
                }
                String customerNumber = m.get("no").toString();
                String idCard = m.get("cardId").toString();
                String name = m.get("name").toString();
                Map params = new HashMap();
                params.put("contactWay", CustomerConstant.CUS_CONTACT_WAY_MOBILE);//联系方式为手机
                params.put("customerNumber", customerNumber);
                //查询重复号码
                List<Contact> contactRepeatList = contactDao.queryContactListForJudgeRepeat(params);
                Contact mainContact;
                Contact contact;
                Boolean isUpdateIdCard = true;
                if(null != m.get("mainContactId")){//该数据是主联系人数据
                    //主联系人id
                    Long mainContactId = Long.parseLong(m.get("mainContactId").toString());
                    mainContact = repository.get(Contact.class, mainContactId);
                    //查询客户历史商机是否已签单
                    List<Map> historyBusinessList = businessAbilityService.getCustomerBusinessList(customerId);
                    if(null != historyBusinessList && historyBusinessList.size() > 0){
                        for (Map bMap: historyBusinessList) {
                            if(null != bMap.get("businessstatus") && (bMap.get("businessstatus").toString().equals(BusinessConstant.BUS_STATUS_SIGNED)
                                    || bMap.get("businessstatus").toString().equals(BusinessConstant.BUS_STATUS_ORDER_SUCCESSED))){//如果有签单的商机，则不能修改客户身份证号码
                                isUpdateIdCard = false;
                            }
                        }
                    }
                    if(null != contactRepeatList && contactRepeatList.size() > 0){//如果存在重复号码
                        if(contactRepeatList.size() > 1){//重复条数大于1，不允许修改
                            return mainContactId;
                        }else if(contactRepeatList.get(0).getId().longValue() == mainContactId){//如果重复号码的联系人是该条主联系人，则可以修改
                            mainContact.setName(name);
//                            mainContact.setNo(customerNumber);
                            mainContact.setContactWay(CustomerConstant.CUS_CONTACT_WAY_MOBILE);
                            mainContact.setCustomerId(customerId);
                            if(null != m.get("relationshipOfCus") && StringUtils.isNotEmpty(m.get("relationshipOfCus").toString())){
                                mainContact.setRelationshipOfCus(m.get("relationshipOfCus").toString());
                            }
                            mainContact.setUpdaterUser(user);
                            repository.saveOrUpdate(mainContact);
                            //修改客户主联系人信息，以及身份证号
                            customer.setUpdaterUser(user);
                            if(isUpdateIdCard){
                                customer.setIdCard(idCard);
                            }
//                            customer.setMainContactNo(customerNumber);
                            customer.setMainContactName(name);
                            if(null != m.get("maritalStatus") && StringUtils.isNotEmpty(m.get("maritalStatus").toString())){
                                customer.setMaritalStatus(m.get("maritalStatus").toString());
                            }
                            if(null != m.get("childrenNum") && StringUtils.isNotEmpty(m.get("childrenNum").toString())){
                                customer.setChildrenNum(Integer.parseInt(m.get("childrenNum").toString()));
                            }
                            repository.saveOrUpdate(customer);
                            customerService.saveCustomerRecord(customerId, customer.getNo(), Contact.TABLE_NAME, mainContact.getId(), CustomerConstant.CUS_OPERATE_CONTACT_UPDATE, user.getId(), "下单修改联系人");
                            return mainContact.getId();
                        }
                    }else {//如果没有重复号码，新增联系人（状态置为主联系人）
                        String relationship = null != m.get("relationshipOfCus") && StringUtils.isNotEmpty(m.get("relationshipOfCus").toString()) ? m.get("relationshipOfCus").toString() : "";
                        //修改客户身份证号
                        customer.setUpdaterUser(user);
                        if(isUpdateIdCard){
                            customer.setIdCard(idCard);
                        }
                        if(null != m.get("maritalStatus") && StringUtils.isNotEmpty(m.get("maritalStatus").toString())){
                            customer.setMaritalStatus(m.get("maritalStatus").toString());
                        }
                        if(null != m.get("childrenNum") && StringUtils.isNotEmpty(m.get("childrenNum").toString())){
                            customer.setChildrenNum(Integer.parseInt(m.get("childrenNum").toString()));
                        }
                        contact = saveContactByPram(keyWorker.nextId(), name, customerNumber, customerId, relationship, user, customer);
                        repository.saveOrUpdate(customer);
                        customerService.saveCustomerRecord(customerId, customer.getNo(), Contact.TABLE_NAME, contact.getId(), CustomerConstant.CUS_OPERATE_CONTACT_SAVE, user.getId(), "下单新增联系人");
                        return contact.getId();
                    }
                }else{//不是主联系人数据，则新增联系人
                    if(null != contactRepeatList && contactRepeatList.size() > 0) {//如果存在重复号码
//                        throw new BizException("修改联系人信息失败！该号码已存在！", 100005);
                        return null;
                    }
                    String relationship = null != m.get("relationshipOfCus") && StringUtils.isNotEmpty(m.get("relationshipOfCus").toString()) ? m.get("relationshipOfCus").toString() : "";
                    contact = saveContactByPram(keyWorker.nextId(), name, customerNumber, customerId, relationship, user, customer);
                    customerService.saveCustomerRecord(customerId, customer.getNo(), Contact.TABLE_NAME, contact.getId(), CustomerConstant.CUS_OPERATE_CONTACT_SAVE, user.getId(), "下单新增联系人");
                    return contact.getId();
                }
            }
        }else {
            throw new BizException("修改联系人信息失败！联系人信息为空！", 10005);
        }
        return null;
    }

     /**
      * 下单新增联系人保存
      * @param id   联系人id
      * @param name 姓名
      * @param no   号码
      * @param customerId   客户id
      * @param relationshipOfCus    与客户关系
      * @param user 操作人
      * @param customer 客户对象
      * @return
      */
    public Contact saveContactByPram(Long id, String name, String no, Long customerId, String relationshipOfCus, User user, Customer customer){
        Contact contact = new Contact();
        contact.setId(id);
        contact.setName(name);
        contact.setNo(no);
        contact.setNoBak(njCodeUtil.decrypt(no));
        contact.setContactWay(CustomerConstant.CUS_CONTACT_WAY_MOBILE);
        contact.setCustomerId(customerId);
        contact.setRelationshipOfCus(relationshipOfCus);
        contact.setCreateUser(user);
        return contactService.updateCusMainContact(contact, user, customer);
    }
}
